/* eslint-disable */
import { computed, nextTick, ref } from 'vue'
import { useStore } from 'vuex'
import { ElMessage, ElMessageBox } from 'element-plus'
import { singleUpload, splitUpload } from '@ruifox-cms/utils'
import { getImageSize, convertHexToBase64, transBase64FromImage, parseRtf } from '@/utils/tools'
import { uploadByUrl } from '@/api/file'
import axios from 'axios'

import tinymce from 'tinymce/tinymce' //tinymce默认hidden，不引入则不显示编辑器
import 'tinymce/themes/silver' //编辑器主题，不引入则报错
import 'tinymce/icons/default' //引入编辑器图标icon，不引入则不显示对应图标
// 引入编辑器插件(几乎免费全部内容)
import 'tinymce/plugins/advlist' //高级列表
import 'tinymce/plugins/anchor' //锚点
import 'tinymce/plugins/autolink' //自动链接
import 'tinymce/plugins/autoresize' //编辑器高度自适应,注：plugins里引入此插件时，Init里设置的height将失效
import 'tinymce/plugins/autosave' //自动存稿
import 'tinymce/plugins/charmap' //特殊字符
import '/public/tinymce/plugins/code' //编辑源码
import 'tinymce/plugins/codesample' //代码示例
import 'tinymce/plugins/directionality' //文字方向
import 'tinymce/plugins/fullscreen' //全屏
import 'tinymce/plugins/hr' //水平分割线
import 'tinymce/plugins/importcss' //引入css
import 'tinymce/plugins/insertdatetime' //插入日期时间
import '/public/tinymce/plugins/link' //超链接
import 'tinymce/plugins/lists' //列表插件
import 'tinymce/plugins/pagebreak' //插入分页符
import 'tinymce/plugins/paste' //粘贴插件
import 'tinymce/plugins/save' //保存
import 'tinymce/plugins/searchreplace' //查找替换
import 'tinymce/plugins/table' //表格
import 'tinymce/plugins/textcolor' //文字颜色
import '@npkg/tinymce-plugins/indent2em'
import '/public/tinymce/plugins/layout' //一键布局
import '/public/tinymce/plugins/formatpainter/plugin.js' //格式刷

/**
 * 创建tinymce编辑器配置
 * @param {Object} options 配置选项
 * @returns {Object} tinymce配置对象
 */
export function createTinyConfig({ fatherStore, editor135, pasteLoading, handlers, showImgOption, currentImg, curHoverImg, showAxupImgs, showVideoUpload, showFilesUpload, isPasting }) {
  let store = useStore()
  if(!store) store = fatherStore
  
  // 从store获取配置
  const clip_port = ref(store.state.content.clip_port || 10086)
  const pluginConfig = computed(() => store.state.content.pluginConfig)
  const singleActionUrl = computed(() => store.state.base.singleActionUrl)
  const splitActionUrl = computed(() => store.state.base.splitActionUrl)
  const maxWidth = computed(() => {
    // 允许上传的图片最大宽度
    let currentSite = store.state.site.currentSite
    return currentSite.setting.maxWidth ? currentSite.setting.maxWidth : 2000
  })
  const { handleImgEditor, setAvatarBase64, onContentFrom135 } = handlers
  let editorMode = localStorage.getItem('toolbarMode') || 1 // 1极简模式 2高级模式
  console.log('editorMode', editorMode);
  
  let toolbar = ref([])
  let toolbar_groups = ref({})
  let menubar = ref('')
  if (editorMode == 1) { // 极简模式
    console.log('极简模式');
    
    toolbar.value = [
      'code fullscreen undo redo',
      'formatselect fontselect fontsizeselect',
      'bold italic forecolor alignleft aligncenter alignright alignjustify searchreplace removeformat layout formatpainter',
      'indent_group',
      'insert_group',
      'table_group',
      'editor_group',
      'media_group'
    ]
    toolbar_groups.value = {
      // code_group: {
      //   text: '代码',
      //   items: 'code fullscreen undo redo'
      // },
      // text_formatting: {
      //   text: '文字格式',
      //   items: 'formatselect fontselect fontsizeselect | bold italic underline strikethrough forecolor backcolor subscript superscript removeformat layout'
      // },
      // list_group: {
      //   text: '格式',
      //   items: 'bold italic underline strikethrough forecolor backcolor selectall searchreplace removeformat layout'
      // },
      // alignment_group: {
      //   icon: 'align-left',
      //   tooltip: '对齐方式',
      //   items: 'alignleft aligncenter alignright alignjustify'
      // },
      
      indent_group: {
        icon: 'indent',
        tooltip: '缩进',
        items: 'bullist numlist | outdent indent indent2em lineheight'
      },
      insert_group: {
        text: '格式',
        items: 'subscript superscript charmap hr insertdatetime | underline strikethrough backcolor selectall'
      },
      table_group: {
        text: '表格',
        items: 'table tabledelete tableinsertrowbefore tableinsertrowafter tabledeleterow tableinsertcolbefore tableinsertcolafter tabledeletecol'
      },
      // tools_group: {
      //   text: '工具',
      //   items: ''
      // },
      editor_group: {
        text: '编辑器',
        items: '135Editor xiumi'
      }
    }
  }else{ // 标准模式
    console.log('标准模式');
    toolbar.value = [
      "code | fullscreen undo redo",
      "formatselect fontselect fontsizeselect | bold italic underline strikethrough forecolor backcolor subscript superscript removeformat layout formatpainter",  // 注意这里的修改
      "bullist | numlist",
      "alignleft aligncenter | alignright alignjustify",
      "outdent indent | indent2em lineheight",
      "charmap hr | \
                 insertdatetime",
      "table tabledelete tableinsertrowbefore tableinsertrowafter | tabledeleterow tableinsertcolbefore tableinsertcolafter tabledeletecol",
      "selectall | searchreplace",
      "135Editor | xiumi",
      "imgsedit axupimgs axupvideo axupfiles onlineImgEdit",
    ]
    toolbar_groups.value = {}
    menubar.value = 'edit insert view format tools table'
  }
  
  return {
    language_url: process.env.BASE_URL + 'tinymce/langs/zh_CN.js',
    language: 'zh_CN',
    toolbar_sticky: true,
    skin_url: process.env.BASE_URL + 'tinymce/skins/ui/oxide',
    inline: true,
    plugins: 'searchreplace autolink directionality fullscreen link code codesample table charmap hr anchor insertdatetime advlist lists pagebreak autosave indent2em layout formatpainter',
    toolbar: toolbar.value,
    toolbar_groups: toolbar_groups,
    layout_options: {
      style: {
        'text-indent': '2em',
        'line-height': '2',
        'font-family': '微软雅黑',
        'font-size': '16px'
      },
      filterTags: ['table>*', 'tbody>*'],
      clearStyle: ['position', 'top', 'bottom'],
      tagsStyle: {
        'p,p>span,span': {
          'text-indent': '2em',
          'line-height': '2',
          'font-family': '微软雅黑',
          'font-size': '16px'
        },
        font: { 'font-family': '微软雅黑' },
        img: { display: 'block', 'margin-left': 'auto', 'margin-right': 'auto', height: 'auto' }
      }
    },
    custom_ui_selector: 'body',
    automatic_uploads: true,
    menubar: menubar.value,
    menu: {
      edit: {
        title: '编辑',
        items: 'undo redo | cut copy paste pastetext | selectall'
      },
      insert: { title: '插入', items: 'link axupimgs axupvideo axupfiles onlineImgEdit |  hr' },
      view: { title: '查看', items: 'visualaid' }
    },
    fontsize_formats: '12px 14px 16px 18px 20px 22px 24px 28px 32px 36px 48px 56px 72px',
    font_formats:
      '微软雅黑=Microsoft YaHei;苹果苹方=PingFang SC;宋体=simsun,serif;仿宋体=FangSong,serif;黑体=SimHei,sans-serif;Arial=arial,helvetica,sans-serif;Arial Black=arial black,avant garde;Book Antiqua=book antiqua,palatino;',
    height: 600,
    placeholder: '',
    icons: 'tinyhcs',
    icons_url: process.env.BASE_URL + 'tinymce/icons/tinyhcs/icons.js',
    extended_valid_elements:
      'svg[*],foreignobject[*],defs[*],pattern[*],desc[*],metadata[*],g[*],mask[*],path[*],line[*],marker[*],rect[*],circle[*],ellipse[*],polygon[*],polyline[*],linearGradient[*],radialGradient[*],stop[*],image[*],view[*],text[*],textPath[*],title[*],tspan[*],glyph[*],symbol[*],switch[*],use[*],img[*]',
    branding: false,
    resize: false,
    statusbar: false,
    elementpath: false,
    fixed_toolbar_container: '#tinymce-box .toolbar',
    content_css: process.env.BASE_URL + 'tinymce/tinycontent.css',
    images_upload_url: singleActionUrl.value,
    convert_urls: false,
    contextmenu: 'link copy myPaste',
    relative_urls: false,

    images_upload_handler: async (blobInfo, success, failure, progress) => {
      let option = {
        file: new File([blobInfo.blob()], blobInfo.filename(), { type: 'image/png' })
      }
      let res = {}
      if (option.file.size > 5 * 1024 * 1024) {
        res = await splitUpload(option.file, splitActionUrl.value, () => {}, 5 * 1024 * 1024)
      } else {
        let data = new FormData()
        data.append('file', option.file)
        const { width, height, scale } = await getImageSize(option.file, maxWidth.value)
        data.append('cropWidth', width)
        data.append('cropHeight', height)
        data.append('scaledWidth', width)
        data.append('scaledHeight', height)
        data.append('startX', 0)
        data.append('startY', 0)
        data.append('path', 'content')
        data.append('type', 0)
        if (scale < 1) {
          data.append('canMini', true)
        }
        res = await singleUpload(data, singleActionUrl.value, () => {})
      }
      console.log('res',res);
      if (res.data.url) {
        success(res.data.url)
        setTimeout(function () {
          const editor = tinymce.activeEditor
          const img = editor.dom.select('img[src="' + res.data.url + '"]')[0]
          if (img) {
            editor.dom.setAttrib(img, 'origin-src', res.data.oriUrl ? res.data.oriUrl : res.data.url)
          }
        }, 100)
      }
    },

    init_instance_callback: function (editor) {
      editor.execCommand('selectAll')
      editor.selection.getRng().collapse(false)
      editor.focus()

      editor.on('paste', evt => {
        const clipboardData = evt.clipboardData
        const isImage = clipboardData.types.length && clipboardData.types.join('').includes('Files')
     
        // 当复制内容不止图片时的处理逻辑
        if (!isImage) {
          console.log('元素粘贴');
          let rtfData = evt.clipboardData.getData("text/rtf")
          console.log('rtfData',rtfData);
          let htmlData = evt.clipboardData.getData("text/html")
          console.log('htmlData',htmlData);
          //------------------------粘贴word核心代码开始-------------------------
          const hexStrings = parseRtf(
            rtfData
          );
          console.log('evt',evt);
          console.log('hexStrings',hexStrings);
          // 获取base64图片数据
          const base64Images = hexStrings.map((hexObj) => {
            let convertHexToBase64Str = convertHexToBase64(hexObj.hex);
            console.log('convertHexToBase64Str',convertHexToBase64Str);
            return convertHexToBase64Str;
          });
          setTimeout(() => {
            const wordImages = tinymce.activeEditor.dom.doc.querySelectorAll('img[src*="file://"]');
            const urlImages = tinymce.activeEditor.dom.doc.querySelectorAll('img[src^="http"]');
            console.log('wordImages',wordImages);
            console.log('urlImages',urlImages);
            urlImages.forEach(item => {
              setAvatarBase64(item.src).then((base64) => {
                console.log('base64',base64);
                item.src = base64
                tinymce.activeEditor.uploadImages();
              })
            })
            //如果图片过大，则不进行上传
            if(!Array.from(wordImages).find((item, index) => base64Images[index])){
              console.log('粘贴内容中存在过大图片，无法粘贴，请使用word导入功能');
              ElMessage({
                showClose: true,
                message: '粘贴内容中存在过大图片，无法粘贴，请使用word导入功能',
                type: 'warning'
              })
              return;
            }
            wordImages.forEach((item, index) => {
              console.log('item',item);
              console.log('index',index);
              console.log('hexStrings[index].type',hexStrings[index]?.type);
              console.log('base64Images[index]',base64Images[index]);
              
              item.src = `data:${hexStrings[index]?.type || 'image/png'};base64,${base64Images[index]}`;
              tinymce.activeEditor.uploadImages();
            });
          }, 200);
          //------------------------粘贴word核心代码结束-------------------------
          return;
        } 
      })

      editor.on('change setContent', function () {
        if (tinymce.activeEditor) {
          let tinyCnt = tinymce.activeEditor.getContent()
          let imgList = []
          if (tinyCnt) {
            imgList = tinymce.activeEditor.dom.select('img')
          }
          if (imgList && imgList.length > 0) {
            imgList.forEach(item => {
              item.onmouseenter = function (e) {
                let btnBox = document.getElementById('img-btn-box')
                btnBox.style.top = e.target.offsetTop + 'px'
                btnBox.style.left = e.target.offsetLeft + 'px'
                showImgOption.value = true
                currentImg.value = item
                curHoverImg.value = item
              }
              item.onmouseleave = function () {
                showImgOption.value = false
              }
            })
          }
        }
      })
    },

    setup: editor => {
      // editor.ui.registry.addButton('imgsedit', {
      //   text: `<div class="image-group"><i class="iconfont">&#xe656;</i><p>编辑图片</p></div>`,
      //   tooltip: '图片批量编辑',
      //   onAction: () => handleImgEditor()
      // })

      // editor.ui.registry.addButton('axupimgs', {
      //   text: `<div class="image-group"><i class="iconfont">&#xe668;</i><p>插入图片</p></div>`,
      //   tooltip: '插入图片',
      //   onAction: () => (showAxupImgs.value = true)
      // })

      // editor.ui.registry.addMenuItem('axupimgs', {
      //   text: '插入图片',
      //   icon: 'axupimgs',
      //   onAction: () => (showAxupImgs.value = true)
      // })

      // editor.ui.registry.addButton('axupvideo', {
      //   text: `<div class="image-group"><i class="iconfont">&#xe659;</i><p>插入视频</p></div>`,
      //   tooltip: '插入视频',
      //   onAction: () => (showVideoUpload.value = true)
      // })

      // editor.ui.registry.addMenuItem('axupvideo', {
      //   text: '插入视频',
      //   icon: 'axupvideo',
      //   onAction: () => (showVideoUpload.value = true)
      // })

      // editor.ui.registry.addButton('axupfiles', {
      //   // text: `<div class="image-group"><i class="iconfont">&#xe61a;</i><p>插入附件</p></div>`,
      //   text: `<div class="image-group"><svg t="1742284418664" class="icon" viewBox="0 0 1248 1024" version="1.1" xmlns="http://www.w3.org/2000/svg" p-id="19772" width="40" height="40"><path stroke="black"stroke-width="2px" style="stroke-width: 2px;" d="M920.97561 494.666927c0 43.957073-36.23961 79.772098-80.771122 79.772097H355.502829C310.971317 574.439024 274.731707 538.624 274.731707 494.666927V79.772098C274.731707 35.790049 310.971317 0 355.502829 0h484.701659c44.531512 0 80.771122 35.790049 80.771122 79.772098v145.857561m-32.318439-145.857561c0-26.374244-21.72878-47.853268-48.452683-47.853269H355.502829c-26.723902 0-48.452683 21.479024-48.452683 47.853269v414.894829c0 26.374244 21.72878 47.853268 48.452683 47.853268h484.701659c26.723902 0 48.452683-21.479024 48.452683-47.853268V79.772098z m-64.611903 414.894829H371.637073a16.059317 16.059317 0 0 1-16.159219-15.98439V446.813659c0-3.721366 1.323707-7.292878 3.69639-10.165074 7.317854-8.741463 73.253463-85.566439 134.643512-85.566439 31.719024 0 52.174049 12.51278 71.929756 24.675903 18.606829 11.438829 36.189659 23.177366 64.936586 23.177366h0.049951c21.10439 0 33.192585-17.358049 52.823414-48.053074 24.775805-38.737171 58.692683-91.810341 136.516683-111.041561a16.234146 16.234146 0 0 1 13.886439 2.897171 15.934439 15.934439 0 0 1 6.218927 12.587708v223.406829c0 8.81639-7.242927 15.959415-16.159219 15.959414z m-16.159219-217.71239c-51.175024 19.281171-75.37639 57.11922-96.980293 90.96117-20.729756 32.36839-40.260683 62.938537-78.922927 62.938537l-2.372683-0.049951c-37.388488-1.24878-60.515902-15.484878-80.920975-27.972683-17.333073-10.689561-32.343415-19.880585-54.846439-19.880586-36.814049 0-85.841171 46.854244-106.021464 69.681952v10.115122h420.064781v-185.793561z m-290.816 10.264975c-35.640195 0-64.611902-28.647024-64.611903-63.837658 0-35.21561 28.971707-63.812683 64.611903-63.812683 35.640195 0 64.636878 28.597073 64.636878 63.812683 0 35.21561-28.971707 63.837659-64.636878 63.837658z m0-95.731512c-17.80761 0-32.318439 14.286049-32.318439 31.918829 0 17.557854 14.485854 31.893854 32.318439 31.893854 17.80761 0 32.318439-14.336 32.318439-31.893854 0-17.63278-14.485854-31.918829-32.318439-31.918829z" fill="#999999" p-id="19773"></path><path d="M574.439024 629.060683V975.047805c0 13.811512-10.739512 25.025561-23.926634 25.025561H23.926634C10.739512 1000.073366 0 988.859317 0 975.047805V474.586537C0 460.775024 10.739512 449.560976 23.926634 449.560976h385.773268" fill="#FFFFFF" p-id="19774"></path><path d="M407.452098 451.309268H56.245073a49.926244 49.926244 0 0 0-49.901268 49.95122v465.270634c0 27.548098 22.353171 49.901268 49.901268 49.901268h465.29561a49.926244 49.926244 0 0 0 49.926244-49.901268V615.324098l-164.014829-163.989854z m135.492682 175.828293v1.123902h-111.44117a35.715122 35.715122 0 0 1-35.640195-35.66517v-112.515122l147.081365 147.081366z m-21.404097 360.797659H56.245073a21.429073 21.429073 0 0 1-21.379122-21.404098v-465.29561c0-11.788488 9.590634-21.379122 21.379122-21.379122h311.096195v112.739903a64.262244 64.262244 0 0 0 64.187317 64.187317h111.39122V966.556098a21.429073 21.429073 0 0 1-21.379122 21.404097z m-144.683707-276.829659l-119.882927-69.182439c-7.692488-4.470634-15.335024-6.743415-22.727805-6.743415-16.359024 0-32.892878 12.013268-32.892878 38.862049v138.389854c0 26.84878 16.533854 38.837073 32.917854 38.837073 7.367805 0 15.010341-2.247805 22.727804-6.693463l119.882927-69.232391c13.661659-7.892293 21.504-19.580878 21.504-32.118634 0-12.487805-7.842341-24.226341-21.528975-32.118634z m-11.963317 43.532488l-119.882927 69.207414c-4.995122 2.897171-8.59161 3.496585-10.739512 3.496586-7.817366 0-8.99122-9.315902-8.99122-14.910439v-138.41483c0-5.569561 1.173854-14.885463 8.99122-14.885463 2.147902 0 5.74439 0.599415 10.739512 3.496585l119.882927 69.182439c5.994146 3.496585 9.590634 7.742439 9.590634 11.413854 0 3.69639-3.596488 7.942244-9.590634 11.413854zM57.244098 513.64839h47.079024v47.079025H57.244098v-47.079025z m0 95.806439h47.079024v47.054049H57.244098v-47.054049z m0 95.781464h47.079024v47.079024H57.244098v-47.079024z m0 95.781463h47.079024v47.079024H57.244098v-47.079024z m0 95.781464h47.079024v47.079024H57.244098v-47.079024z m406.003512-191.562927h47.079024v47.079024h-47.079024v-47.079024z m0 95.781463h47.079024v47.079024h-47.079024v-47.079024z m0 95.781464h47.079024v47.079024h-47.079024v-47.079024z" fill="#999999" p-id="19775"></path><path d="M878.891707 424.585366h298.083903C1216.636878 424.585366 1248.780488 455.330341 1248.780488 493.268293v462.04878c0 37.937951-32.14361 68.682927-71.804878 68.682927h-430.829269C706.485073 1024 674.341463 993.255024 674.341463 955.317073V614.025366" fill="#FFFFFF" p-id="19776"></path><path d="M874.221268 424.585366H1198.08C1226.052683 424.585366 1248.780488 445.814634 1248.780488 471.914146v504.757074C1248.780488 1002.770732 1226.052683 1024 1198.08 1024H725.041951c-27.972683 0-50.700488-21.229268-50.700488-47.32878V611.153171c0-12.562732 5.294829-24.625951 14.810537-33.492293l149.10439-139.214049a52.948293 52.948293 0 0 1 35.964878-13.836488z m0 31.494244a17.482927 17.482927 0 0 0-11.963317 4.595512l-149.204292 139.288976a15.210146 15.210146 0 0 0-4.89522 11.164097v365.468098c0 8.741463 7.592585 15.734634 16.858537 15.734634h473.013073c9.340878 0 16.858537-7.068098 16.858536-15.734634V471.914146c0-8.741463-7.592585-15.734634-16.858536-15.734634H874.221268v-0.099902z m41.184781 300.781268l24.151414-22.028488 80.920976 77.324488a8.491707 8.491707 0 0 0 11.313951 0.249756l5.944195-5.12a7.192976 7.192976 0 0 0 0.39961-10.739512l-0.149854-0.124878-160.343414-153.275317c-14.910439-14.261073-39.786146-13.836488-55.69561 1.398634-16.15922 15.384976-16.558829 39.786146-1.42361 54.197073l176.352781 168.510439c25.724878 24.625951 68.508098 23.876683 95.581658-2.072975 27.323317-26.099512 28.122537-67.584 2.147903-92.33483l-97.90439-93.683512 24.17639-22.053463 97.954341 93.608585c38.961951 37.26361 37.863024 98.279024-2.147902 136.491707-40.210732 38.387512-104.747707 39.561366-143.959415 2.072976l-176.35278-168.510439c-28.197463-26.898732-27.323317-70.830829 1.423609-98.328976 28.971707-27.648 75.626146-28.472195 103.973464-1.398634L1062.11278 774.243902a37.288585 37.288585 0 0 1-1.498536 56.045269l-5.91922 5.095024a44.081951 44.081951 0 0 1-58.517853-1.323707l-80.771122-77.174634z" fill="#999999" p-id="19777"></path></svg><p>插入附件</p></div>`,
      //   tooltip: '插入附件',
      //   onAction: () => (showFilesUpload.value = true)
      // })

      editor.ui.registry.addMenuItem('axupfiles', {
        text: '插入附件',
        icon: 'axupfiles',
        onAction: () => (showFilesUpload.value = true)
      })

      
      editor.ui.registry.addButton('135Editor', {
        icon: '135editor',
        tooltip: '135编辑器',
        onAction: () => {
          editor135 = window.open(
            'https://www.135editor.com/beautify_editor.html?callback=true&appkey=',
            '135editor',
            'height=' + (window.screen.availHeight - 100) + ',width=' + (window.screen.availWidth - 100) + ',top=50,left=50,help=no,resizable=no,status=no,scroll=no'
          )
          window.removeEventListener('message', onContentFrom135)
          window.addEventListener('message', onContentFrom135, false)
        }
      })

      editor.ui.registry.addButton('xiumi', {
        icon: 'xiumi',
        tooltip: 'xiumi编辑器',
        onAction: () => {
          window.open(
            process.env.BASE_URL + 'xiumi/xiumi-ue-dialog-v5.html',
            'xiumiEditor',
            'height=' + (window.screen.availHeight - 100) + ',width=' + (window.screen.availWidth - 100) + ',top=50,left=50,help=no,resizable=no,status=no,scroll=no'
          )
        }
      })

      editor.ui.registry.addMenuItem('myPaste', {
        text: '粘贴',
        icon: 'paste-text', // 指定菜单项的图标
        shortcut: 'Ctrl+V', // 指定快捷键
        onAction: function () {
          console.log(tinymce.activeEditor, 78787878)
          // 在这里编写自定义菜单项的处理逻辑
          if (pluginConfig.value.isUse) {
            /*
             * app内容处理粘贴
             * 1.直接调用10086端口
             * 2.如果可以调用直接使用，不能调用则看唤醒协议是否支持
             * 3.try catch不支持唤醒协议则访问下载链接
             * */
            // const url = "http://127.0.0.1:10086/clip"
            pasteLoading.value = true
            const checkPromise = url => {
              return new Promise((resolve, reject) => {
                axios
                  .get(url)
                  .then(res => {
                    if (res.data.code) resolve(res)
                    else reject()
                  })
                  .catch(() => {
                    reject()
                  })
              })
            }
            const precheckClipPort = () => {
              const url = 'http://127.0.0.1:' + clip_port.value + '/clip'
              return checkPromise(url)
                .then(res => {
                  pasteLoading.value = false
                  if (res.data.code === 200) {
                    editor.insertContent(res.data.data)
                  } else {
                    ElMessage({
                      message: '无法粘贴该内容',
                      type: 'warning'
                    })
                  }
                  pasteLoading.value = false
                })
                .catch(() => {
                  if (clip_port.value < 10089) {
                    clip_port.value++
                    precheckClipPort()
                  } else {
                    ElMessageBox.confirm('无法粘贴该内容，是否启用粘贴插件工具', '启用确认', {
                      confirmButtonText: '启用',
                      cancelButtonText: '暂不启用'
                    })
                      .then(() => {
                        clip_port.value = store.state.content.clip_port
                        const foxClipLink = document.createElement('a')
                        foxClipLink.href = 'foxc://'
                        foxClipLink.target = '_self'
                        foxClipLink.click()
                        isPasting.value = false
                        nextTick(() => {
                          isPasting.value = true
                        })
                        // 判断用户界面失焦
                        let userOnblur = false
                        window.onblur = function () {
                          userOnblur = true
                        }
                        setTimeout(() => {
                          if (!userOnblur) {
                            ElMessageBox.confirm('<div><p style="font-size: 16px;margin-bottom: 15px;">下载粘贴插件工具，下载文件包内含安装步骤</p></div>', '下载确认', {
                              distinguishCancelAndClose: true,
                              dangerouslyUseHTMLString: true,
                              confirmButtonText: '确认下载',
                              cancelButtonText: '暂不安装（本次发布不使用插件）'
                            })
                              .then(() => {
                                window.open(pluginConfig.value.downloadLink)
                              })
                              .catch(action => {
                                if (action === 'cancel') pluginConfig.value.isUse = false
                              })
                          }
                        }, 300)
                        pasteLoading.value = false
                      })
                      .catch(() => {
                        pluginConfig.value.isUse = false
                        pasteLoading.value = false
                      })
                  }
                })
            }
            precheckClipPort()
          } else {
            // 未开启插件时的粘贴处理
            navigator.clipboard
              .read()
              .then(async items => {
                if (pasteLoading.value) return
                pasteLoading.value = true

                try {
                  // 处理所有剪贴板项
                  for (const item of items) {
                    // 处理HTML内容(包含图片)
                    if (item.types.includes('text/html')) {
                      const htmlBlob = await item.getType('text/html')
                      const htmlContent = await htmlBlob.text()
                      editor.insertContent(htmlContent)
                    }
                    // 如果没有HTML内容，则尝试纯文本
                    else if (item.types.includes('text/plain')) {
                      const text = await item.getType('text/plain')
                      const textContent = await text.text()
                      editor.insertContent(textContent)
                    }
                  }

                  // 处理网络图片和本地图片
                  setTimeout(() => {
                    const wordImages = tinymce.activeEditor.dom.doc.querySelectorAll('img[src*="file://"]')
                    const urlImages = tinymce.activeEditor.dom.doc.querySelectorAll('img[src^="http"]')
                    const baseUrl = store.state.base.groupSetting.baseUrl || ''

                    // 处理网络图片
                    for(let item of urlImages){
                      // 如果不是本地图片，则上传
                      if(!item.src.includes(baseUrl)){
                        uploadByUrl({url: item.src}).then(res => {
                          item.src = res.data ? res.data : item.src
                        })
                      }
                    }

                    // 处理本地图片
                    if (wordImages.length > 0) {
                      const hexStrings = parseRtf(evt.clipboardData.getData('text/rtf'))
                      const base64Images = hexStrings.map(hexObj => {
                        return convertHexToBase64(hexObj.hex)
                      })

                      wordImages.forEach((item, index) => {
                        item.src = `data:${hexStrings[index].type};base64,${base64Images[index]}`
                        tinymce.activeEditor.uploadImages()
                      })
                    }
                  }, 200)
                } catch (err) {
                  console.error('Failed to process clipboard content:', err)
                  ElMessage({
                    message: '无法粘贴该内容',
                    type: 'warning'
                  })
                } finally {
                  pasteLoading.value = false
                }
              })
              .catch(err => {
                console.error('Failed to read clipboard:', err)
                pasteLoading.value = false
                ElMessage({
                  message: '无法粘贴该内容',
                  type: 'warning'
                })
              })
          }
        }
      })
    }
  }
}
